//
//  AchievementVC.m
//  NewPro
//
//  Created by 何荧红 on 2018/10/1.
//  Copyright © 2018 何荧红. All rights reserved.
//

#import "AchievementVC.h"
#import "AchievementCell.h"
#import "AchievementModel.h"
#import "AchievementDetailVC.h"
#import "AchievementStore.h"

@interface AchievementVC ()<UITableViewDelegate,UITableViewDataSource>
@property (nonatomic, strong) UITableView *TableView;
@property (nonatomic, strong) NSMutableArray *dataArr;
@property (nonatomic, copy) NSString *year;
@property (nonatomic, copy) NSString *month;
@property (nonatomic, strong) ViewHeader *header;
@property (nonatomic, copy) NSString *seletime;

@end

@implementation AchievementVC

- (NSMutableArray *)dataArr{
    if (!_dataArr) {
        _dataArr = [[NSMutableArray alloc]initWithObjects:@"",@"",@"", nil];
    }
    return _dataArr;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title = @"业绩";
    
    [self initCSS];
    [self GetInfo];
    [self loadData];
    [self loadfrist];
    [self loadSec];
}
- (void)GetInfo{
    [[[AchievementStore alloc]init] GetAmountSuccess:^(NSDictionary * _Nonnull res) {
        if ([res[@"msg"] isEqualToString:@"success"]) {
            self.header.AchieveFTitle.text = [res[@"data"][@"allyNumber"] stringValue];
            self.header.AchieveSTitle.text = [res[@"data"][@"merchantNumber"] stringValue];
        }else{
            
        }
    } Failure:^(NSError * _Nonnull error) {
        [self showMBPError:[HttpTool handleError:error]];
    }];
}
- (void)loadData{
    NSDateFormatter *year = [[NSDateFormatter alloc] init];
    year.dateFormat = @"yyyy";
    NSDateFormatter *month = [[NSDateFormatter alloc] init];
    month.dateFormat = @"MM";
    NSDate *data = [NSDate date];
    [[[AchievementStore alloc]init] GetAchievementWithPrams:@{@"month":[month stringFromDate:data],@"year":[year stringFromDate:data]} Success:^(NSDictionary * _Nonnull res) {
        if ([res[@"msg"] isEqualToString:@"success"]) {
            NSArray *arr = res[@"data"][@"items"];
            if (arr.count > 0) {
                AchievementModel * model = [AchievementModel mj_objectWithKeyValues:arr[0]];
                if (self.dataArr.count > 0) {
                    [self.dataArr replaceObjectAtIndex:0 withObject:model];
                }
            }
        }
        if ([self isDataArrOK]) {
            [self.TableView reloadData];
            [self.TableView.mj_header endRefreshing];
        }
    } Failure:^(NSError * _Nonnull error) {
       [self showMBPError:[HttpTool handleError:error]];
    }];
}
- (void)loadfrist{
    NSDateFormatter *year = [[NSDateFormatter alloc] init];
    year.dateFormat = @"yyyy";
    NSDateFormatter *month = [[NSDateFormatter alloc] init];
    month.dateFormat = @"MM";
    NSDate *data = [NSDate date];
    NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    NSDateComponents *lastMonthComps = [[NSDateComponents alloc] init];
    [lastMonthComps setMonth:-1];
    NSDate *newdate = [calendar dateByAddingComponents:lastMonthComps toDate:data options:0];
    [[[AchievementStore alloc]init] GetAchievementWithPrams:@{@"month":[month stringFromDate:newdate],@"year":[year stringFromDate:newdate]} Success:^(NSDictionary * _Nonnull res) {
        if ([res[@"msg"] isEqualToString:@"success"]) {
            NSArray *arr = res[@"data"][@"items"];
            if (arr.count > 0) {
                AchievementModel * model = [AchievementModel mj_objectWithKeyValues:arr[0]];
                if (self.dataArr.count > 0) {
                    [self.dataArr replaceObjectAtIndex:1 withObject:model];
                }
            }
        }
        if ([self isDataArrOK]) {
            [self.TableView reloadData];
            [self.TableView.mj_header endRefreshing];
        }
    } Failure:^(NSError * _Nonnull error) {
        [self.TableView.mj_header endRefreshing];
        [self showMBPError:[HttpTool handleError:error]];
    }];
}
- (BOOL)isDataArrOK{
    BOOL ISOK = NO;
    for (id obj in self.dataArr) {
        if ([obj isKindOfClass:[NSString class]]) {
            return NO;
        }else if([obj isKindOfClass:[AchievementModel class]]){
            ISOK = YES;
        }
    }
    return ISOK;
}
- (void)loadSec{
    NSDateFormatter *year = [[NSDateFormatter alloc] init];
    year.dateFormat = @"yyyy";
    NSDateFormatter *month = [[NSDateFormatter alloc] init];
    month.dateFormat = @"MM";
    NSDate *data = [NSDate date];
    NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    NSDateComponents *lastMonthComps = [[NSDateComponents alloc] init];
    [lastMonthComps setMonth:-2];
    NSDate *newdate = [calendar dateByAddingComponents:lastMonthComps toDate:data options:0];
    [[[AchievementStore alloc]init] GetAchievementWithPrams:@{@"month":[month stringFromDate:newdate],@"year":[year stringFromDate:newdate]} Success:^(NSDictionary * _Nonnull res) {
        if ([res[@"msg"] isEqualToString:@"success"]) {
            NSArray *arr = res[@"data"][@"items"];
            if (arr.count > 0) {
                AchievementModel * model = [AchievementModel mj_objectWithKeyValues:arr[0]];
                if (self.dataArr.count > 0) {
                    [self.dataArr replaceObjectAtIndex:2 withObject:model];
                }
            }
        }
        if ([self isDataArrOK]) {
            [self.TableView reloadData];
            [self.TableView.mj_header endRefreshing];
        }
    } Failure:^(NSError * _Nonnull error) {
        [self.TableView.mj_header endRefreshing];
        [self showMBPError:[HttpTool handleError:error]];
    }];
}
- (void)initCSS{
    WS(weakself)
    self.header = [[ViewHeader alloc]initWithAchievementHeader];
    [self.header setAchievetoTimeBlock:^{
        [weakself ChooseTime];
    }];
    [self.header setAchieveTimeSearchBlock:^{
        [weakself GetInfo];
        [weakself upData];
    }];
    [self.view addSubview:self.header];
    [self.header mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.height.mas_equalTo(120);
        make.left.right.top.equalTo(self.view);
    }];
    
    self.TableView = [[UITableView alloc]initWithFrame:CGRectMake(0, iPhoneX_Top, ScreenWidth, ScreenHeight - (iPhoneX_Top)) style:UITableViewStyleGrouped];
    [self.TableView registerNib:[UINib nibWithNibName:@"AchievementCell" bundle:nil] forCellReuseIdentifier:@"AchievementCellID"];
    self.TableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.TableView.showsVerticalScrollIndicator = NO;
    self.TableView.delegate = self;
    self.TableView.dataSource = self;
    self.TableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        self.dataArr = [[NSMutableArray alloc]initWithObjects:@"",@"",@"", nil];
        [self GetInfo];
        [self loadData];
        [self loadfrist];
        [self loadSec];
    }];
    [self.view insertSubview:self.TableView belowSubview:self.header];
    [self.TableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view.mas_left);
        make.right.equalTo(self.view.mas_right);
        make.bottom.equalTo(self.view.mas_bottom);
        make.top.equalTo(self.header.mas_bottom);
    }];
    NSDateFormatter *year = [[NSDateFormatter alloc] init];
    year.dateFormat = @"yyyy";
    NSDateFormatter *month = [[NSDateFormatter alloc] init];
    month.dateFormat = @"MM";
    NSDate *data = [NSDate date];
    self.year = [year stringFromDate:data];
    self.month = [month stringFromDate:data];
}
- (void)ChooseTime{
    NSDate *minDate = [NSDate setYear:1978 month:3 day:12];
    NSDate *maxDate = [NSDate date];
    [BRDatePickerView showDatePickerWithTitle:@"选择日期" dateType:BRDatePickerModeYM defaultSelValue:self.seletime minDate:minDate maxDate:maxDate isAutoSelect:YES themeColor:nil resultBlock:^(NSString *selectValue) {
        NSArray *listArr = [selectValue componentsSeparatedByString:@"-"];
        self.header.AchieveTimelab.text = [NSString stringWithFormat:@"%@年%@月",listArr[0],listArr[1]];
        self.seletime = selectValue;
        self.year = listArr[0];
        self.month = listArr[1];
    } cancelBlock:^{

    }];
}
- (void)upData{
    [[[AchievementStore alloc]init] GetAchievementWithPrams:@{@"month":self.month,@"year":self.year} Success:^(NSDictionary * _Nonnull res) {
        if ([res[@"msg"] isEqualToString:@"success"]) {
            NSArray *arr = res[@"data"][@"items"];
            if (arr.count > 0) {
                self.dataArr = [AchievementModel mj_objectArrayWithKeyValuesArray:arr];
            }
        }
        [self.TableView reloadData];
        [self.TableView.mj_header endRefreshing];
    } Failure:^(NSError * _Nonnull error) {
        [self.TableView.mj_header endRefreshing];
        [self showMBPError:[HttpTool handleError:error]];
    }];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    if ([[self.dataArr firstObject] isKindOfClass:[NSString class]]) {
        return 0;
    }else{
        return self.dataArr.count;
    }
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 1;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 192;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 27;
}
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    AchievementModel *model = self.dataArr[section];
    UIView *header = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 27)];
    header.backgroundColor = [UIColor colorWithHexString:@"f1f1f1"];
    UILabel *title = [[UILabel alloc]initWithFrame:CGRectMake(14, 7.5, SCREEN_WIDTH - 30, 12)];
    title.font = [UIFont fontWithName:@"PingFang-SC-Regular" size:12];
    title.textColor = [UIColor colorWithHexString:@"666666"];
    title.text = [NSString stringWithFormat:@"%@年%@月",[model.time substringWithRange:NSMakeRange(0, 4)],[model.time substringWithRange:NSMakeRange(5, 2)]];
    [header addSubview:title];
    return header;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0.01f;
}
-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    return nil;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    AchievementCell *cell = [tableView dequeueReusableCellWithIdentifier:@"AchievementCellID"];
    if (self.dataArr.count > 0) {
        AchievementModel *model = self.dataArr[indexPath.section];
        cell.model = model;
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    AchievementModel *model = self.dataArr[indexPath.section];
    AchievementDetailVC *VC = [[AchievementDetailVC alloc] init];
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    formatter.dateFormat = @"yyyy-MM";
    NSDateFormatter *formatter1 = [[NSDateFormatter alloc] init];
    formatter1.dateFormat = @"yyyy-MM-dd";
    NSDate *data = [NSDate date];
    NSString *dateString = [formatter stringFromDate:data];
    NSString *dataString1 = [formatter1 stringFromDate:data];
    if ([model.time isEqualToString:dateString]) {
        VC.muttime = dataString1;
    }else{
        VC.muttime = [NSString stringWithFormat:@"%@-01",model.time];
    }
    [VC setHidesBottomBarWhenPushed:YES];
    [self.navigationController pushViewController:VC animated:YES];
}
//- (NSString *)getMonthFirstAndLastDayWith:(NSString *)dateStr{
//    NSDateFormatter *format=[[NSDateFormatter alloc] init];
//    [format setDateFormat:@"yyyy-MM-dd"];
//    NSDate *newDate=[format dateFromString:dateStr];
//    double interval = 0;
//    NSDate *firstDate = nil;
//    NSDate *lastDate = nil;
//    NSCalendar *calendar = [NSCalendar currentCalendar];
//    BOOL OK = [calendar rangeOfUnit:NSCalendarUnitMonth startDate:& firstDate interval:&interval forDate:newDate];
//    if (OK) {
//        lastDate = [firstDate dateByAddingTimeInterval:interval - 1];
//    }else {
//        return @"";
//    }
//    NSDateFormatter *myDateFormatter = [[NSDateFormatter alloc] init];
//    [myDateFormatter setDateFormat:@"yyyy-MM-dd"];
////    NSString *firstString = [myDateFormatter stringFromDate: firstDate];
//    NSString *lastString = [myDateFormatter stringFromDate: lastDate];
//    return lastString;
//}


@end
